﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace HEFramework
{
    public static class UnityObjectComponentSystem
    {
        [EntitySystem]
        public class UnityObjectComponentAwakeSystem : AwakeSystem<UnityObjectComponent>
        {
            protected override void Awake(UnityObjectComponent _self)
            {
            }
        }


        [EntitySystem]
        public class UnityObjectComponentDestroySystem : DestroySystem<UnityObjectComponent>
        {
            protected override void Destroy(UnityObjectComponent _self)
            {
                foreach (var value in _self.Maps.Values)
                {
                    value.Dispose();
                }

                _self.Maps.Clear();
            }
        }


        public static T Get<T>(this UnityObjectComponent _self, GameObject _gameObject) where T : UnityEngine.Object
        {
            DictionaryObject<Type, UnityEngine.Object> dic;
            int id = _gameObject.GetInstanceID();
            _self.Maps.TryGetValue(id, out dic);
            if (dic == null)
            {
                dic = DictionaryObject<Type, UnityEngine.Object>.Create();
                _self.Maps.Add(id, dic);
            }

            Type type = typeof(T);
            UnityEngine.Object obj;
            dic.TryGetValue(type, out obj);
            if (obj == null)
            {
                obj = _gameObject.GetComponent<T>();
                if (obj != null)
                {
                    dic.Add(type, obj);
                }
            }

            return (T)obj;
        }
    }
}